<template>
  <div class="amap-debug">
    <el-card header="高德地图API调试工具">
      <el-form :model="debugForm" label-width="120px">
        <el-form-item label="API Key">
          <el-input v-model="debugForm.apiKey" placeholder="输入你的API Key" />
        </el-form-item>
        
        <el-form-item label="测试项目">
          <el-checkbox-group v-model="debugForm.tests">
            <el-checkbox label="staticmap">静态地图API</el-checkbox>
            <el-checkbox label="search">关键字搜索API</el-checkbox>
            <el-checkbox label="regeo">逆地理编码API</el-checkbox>
            <el-checkbox label="geo">地理编码API</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="runTests" :loading="testing">
            开始测试
          </el-button>
          <el-button @click="clearResults">清空结果</el-button>
        </el-form-item>
      </el-form>
      
      <el-divider>测试结果</el-divider>
      
      <div v-for="result in testResults" :key="result.name" class="test-result">
        <el-alert
          :title="result.name"
          :type="result.success ? 'success' : 'error'"
          :description="result.message"
          show-icon
          :closable="false"
        />
        
        <div v-if="result.url" class="test-url">
          <strong>测试URL:</strong>
          <el-input v-model="result.url" readonly>
            <template #append>
              <el-button @click="copyUrl(result.url)">复制</el-button>
            </template>
          </el-input>
        </div>
        
        <div v-if="result.data" class="test-data">
          <strong>返回数据:</strong>
          <pre>{{ JSON.stringify(result.data, null, 2) }}</pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const testing = ref(false)
const testResults = ref([])

const debugForm = reactive({
  apiKey: '',
  tests: ['staticmap', 'search', 'regeo']
})

// 测试静态地图API
async function testStaticMap(apiKey) {
  const url = `https://restapi.amap.com/v3/staticmap?key=${apiKey}&location=116.397428,39.90923&zoom=13&size=400*300&scale=2`
  
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => {
      resolve({
        name: '静态地图API',
        success: true,
        message: '静态地图加载成功',
        url: url
      })
    }
    img.onerror = () => {
      resolve({
        name: '静态地图API',
        success: false,
        message: '静态地图加载失败，可能是API Key权限不足',
        url: url
      })
    }
    img.src = url
  })
}

// 测试JSONP API
function testJsonpApi(apiUrl, testName) {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    const callbackName = 'testCallback_' + Date.now()
    
    window[callbackName] = function(data) {
      document.head.removeChild(script)
      delete window[callbackName]
      
      if (data.status === '1') {
        resolve({
          name: testName,
          success: true,
          message: 'API调用成功',
          url: apiUrl,
          data: data
        })
      } else {
        resolve({
          name: testName,
          success: false,
          message: `API调用失败: ${data.info || '未知错误'}`,
          url: apiUrl,
          data: data
        })
      }
    }
    
    script.onerror = () => {
      document.head.removeChild(script)
      delete window[callbackName]
      resolve({
        name: testName,
        success: false,
        message: '网络请求失败',
        url: apiUrl
      })
    }
    
    script.src = `${apiUrl}&callback=${callbackName}`
    document.head.appendChild(script)
    
    // 超时处理
    setTimeout(() => {
      if (window[callbackName]) {
        document.head.removeChild(script)
        delete window[callbackName]
        resolve({
          name: testName,
          success: false,
          message: '请求超时',
          url: apiUrl
        })
      }
    }, 10000)
  })
}

// 运行所有测试
async function runTests() {
  if (!debugForm.apiKey) {
    ElMessage.warning('请输入API Key')
    return
  }
  
  testing.value = true
  testResults.value = []
  
  try {
    for (const test of debugForm.tests) {
      let result
      
      switch (test) {
        case 'staticmap':
          result = await testStaticMap(debugForm.apiKey)
          break
          
        case 'search':
          result = await testJsonpApi(
            `https://restapi.amap.com/v3/place/text?key=${debugForm.apiKey}&keywords=北京&city=北京`,
            '关键字搜索API'
          )
          break
          
        case 'regeo':
          result = await testJsonpApi(
            `https://restapi.amap.com/v3/geocode/regeo?key=${debugForm.apiKey}&location=116.397428,39.90923`,
            '逆地理编码API'
          )
          break
          
        case 'geo':
          result = await testJsonpApi(
            `https://restapi.amap.com/v3/geocode/geo?key=${debugForm.apiKey}&address=北京市朝阳区`,
            '地理编码API'
          )
          break
      }
      
      if (result) {
        testResults.value.push(result)
      }
    }
  } catch (error) {
    console.error('测试过程中出错:', error)
    ElMessage.error('测试过程中出错')
  } finally {
    testing.value = false
  }
}

// 清空结果
function clearResults() {
  testResults.value = []
}

// 复制URL
function copyUrl(url) {
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('URL已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}
</script>

<style scoped>
.amap-debug {
  max-width: 800px;
  margin: 20px auto;
}

.test-result {
  margin: 15px 0;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.test-url {
  margin: 10px 0;
}

.test-data {
  margin: 10px 0;
}

.test-data pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  font-size: 12px;
}
</style>